/*
 * Copyright (C) 2009 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see <http://www.gnu.org/licenses/>.
 */
package ch.trackedbean.binding.mapping;

import java.util.Map.*;
import ch.trackedbean.binding.beanSpec.*;
import ch.trackedbean.validator.*;

/**
 * {@link IGroupValidator} with {@link ValidationResult} to {@link IBeanStatus} mapping.<br>
 * Use this base class for validator delegating the Validation to a {@link IBusinessValidator}.
 * 
 * @author M. Hautle
 */
public abstract class AbstractBusinessValidator implements IGroupValidator {
	/**
	 * Mapps the validation result on the corresponding properties.
	 * 
	 * @param res The validtion result
	 * @param bean The 'base' bean
	 * @param status The status of the 'base' bean
	 */
	protected void process(ValidationResult res, Object bean, IBeanStatus status) {
		if (res.isBeanValid())
			return;
		// map the validaton results
		for (Entry<String, IErrorDescription[]> entry : res.getAllErrors().entrySet()) {
			String property = entry.getKey();
			// if it's a nested property then get the "end" object
			final int lastIndex = property.lastIndexOf('.');
			if (lastIndex > 0)
				try {
					final String path = property.substring(0, lastIndex);
					status = BeanStatusImpl.getBeanStatus(bean, path);
					property = property.substring(lastIndex + 1);
				} catch (final Exception e) {
					e.printStackTrace();
					continue;
				}
			status.setStatus(property, BeanStatusFlag.ERROR, ValidatorManager.buildErrorString(entry.getValue()));
		}
	}
}
